package com.lfy.yunpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.yunpicture.annotation.AuthCheck;
import com.lfy.yunpicture.common.BaseResponse;
import com.lfy.yunpicture.common.DeleteRequest;
import com.lfy.yunpicture.common.ErrorCode;
import com.lfy.yunpicture.common.ResultUtils;
import com.lfy.yunpicture.constant.UserConstant;
import com.lfy.yunpicture.exception.BusinessException;
import com.lfy.yunpicture.exception.ThrowUtils;
import com.lfy.yunpicture.manager.auth.annotate.SaSpaceCheckPermission;
import com.lfy.yunpicture.manager.auth.model.SpaceUserPermissionConstant;
import com.lfy.yunpicture.model.dto.spaceuser.SpaceUserAddRequest;
import com.lfy.yunpicture.model.dto.spaceuser.SpaceUserEditRequest;
import com.lfy.yunpicture.model.dto.spaceuser.SpaceUserQueryRequest;
import com.lfy.yunpicture.model.dto.spaceuser.SpaceUserUpdateRequest;
import com.lfy.yunpicture.model.entity.SpaceUser;
import com.lfy.yunpicture.model.entity.User;
import com.lfy.yunpicture.model.vo.SpaceUserVO;
import com.lfy.yunpicture.service.SpaceUserService;
import com.lfy.yunpicture.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 团队空间成员接口
 */
@RestController
@RequestMapping("/spaceUser")
@Slf4j
public class SpaceUserController {
    @Resource
    private SpaceUserService spaceUserService;

    // region 增删改查

    /**
     * 创建团队空间成员
     *
     * @param spaceUserAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Long> addSpaceUser(@RequestBody SpaceUserAddRequest spaceUserAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        //在此处将实体类和 DTO 进行转换
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserAddRequest, spaceUser);
        // 数据校验
        spaceUserService.validSpaceUser(spaceUser, true);
        // 填充默认值
        if(spaceUserAddRequest.getSpaceRole() == null){
            spaceUser.setSpaceRole(SpaceUserPermissionConstant.PICTURE_VIEW);
        }
        // 写入数据库
        boolean result = spaceUserService.save(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newSpaceUserId = spaceUser.getId();
        return ResultUtils.success(newSpaceUserId);
    }

    /**
     * 删除团队空间成员
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> deleteSpaceUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        SpaceUser oldSpaceUser = spaceUserService.getById(id);
        ThrowUtils.throwIf(oldSpaceUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceUserService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新团队空间成员（仅管理员可用）
     *
     * @param spaceUserUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpaceUser(@RequestBody SpaceUserUpdateRequest spaceUserUpdateRequest) {
        if (spaceUserUpdateRequest == null || spaceUserUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserUpdateRequest, spaceUser);
        // 数据校验
        spaceUserService.validSpaceUser(spaceUser, false);
        // 判断是否存在
        long id = spaceUserUpdateRequest.getId();
        SpaceUser oldSpaceUser = spaceUserService.getById(id);
        ThrowUtils.throwIf(oldSpaceUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceUserService.updateById(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取团队空间创立者（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<SpaceUserVO> getSpaceUserVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        SpaceUser spaceUser = spaceUserService.getById(id);
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(spaceUserService.getSpaceUserVO(spaceUser, request));
    }

    /**
     * 分页获取团队空间成员列表（仅管理员可用）
     *
     * @param spaceUserQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SpaceUser>> listSpaceUserByPage(@RequestBody SpaceUserQueryRequest spaceUserQueryRequest) {
        long current = spaceUserQueryRequest.getCurrent();
        long size = spaceUserQueryRequest.getPageSize();
        // 查询数据库
        Page<SpaceUser> spaceUserPage = spaceUserService.page(new Page<>(current, size),
                spaceUserService.getQueryWrapper(spaceUserQueryRequest));
        return ResultUtils.success(spaceUserPage);
    }

    /**
     * 分页获取团队空间成员列表（封装类）
     *
     * @param spaceUserQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Page<SpaceUserVO>> listSpaceUserVOByPage(@RequestBody SpaceUserQueryRequest spaceUserQueryRequest,
                                                                 HttpServletRequest request) {
        long current = spaceUserQueryRequest.getCurrent();
        long size = spaceUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<SpaceUser> spaceUserPage = spaceUserService.page(new Page<>(current, size),
                spaceUserService.getQueryWrapper(spaceUserQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceUserService.getSpaceUserVOPage(spaceUserPage, request));
    }

    /**
     * 编辑团队空间成员（给用户使用）
     *
     * @param spaceUserEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.SPACE_USER_MANAGE)
    public BaseResponse<Boolean> editSpaceUser(@RequestBody SpaceUserEditRequest spaceUserEditRequest, HttpServletRequest request) {
        if (spaceUserEditRequest == null || spaceUserEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //在此处将实体类和 DTO 进行转换
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserEditRequest, spaceUser);
        // 数据校验
        spaceUserService.validSpaceUser(spaceUser, false);
        // 判断是否存在
        long id = spaceUserEditRequest.getId();
        SpaceUser oldSpaceUser = spaceUserService.getById(id);
        ThrowUtils.throwIf(oldSpaceUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceUserService.updateById(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
